<template>
	<div>
		<div style='padding:30px 50px;background: #fff'>
			<div style='display: flex;justify-content: space-between;color:#464C5B'>
				<div>
					<span style="font-size:16px;margin-right: 8px">数据表</span>
					<Dropdown trigger="click" @on-click='searchTable'>
		                <Button type="ghost" size="small" style='padding:3px 8px;width:120px;'>
		                    <span class='search-data' :class="{'not_select':search_data.table == ''}" style="padding-top: 2px;">{{search_data.table ? search_data.table : '请选择'}}</span>
		                    <div style='transform:scale(0.5);float: right'>
		                    	<Icon type="chevron-down" size='20'></Icon>
		                    </div>
		                </Button>
		                <DropdownMenu slot="list" style='width:116px'>
		                	<DropdownItem name="">请选择</DropdownItem>
		                    <DropdownItem v-for="item in configData.table" :name="item.Name" :key="item">{{item.Name}}</DropdownItem>
		                </DropdownMenu>
		            </Dropdown>
				</div>
				<div>
					<span style="font-size:16px;margin-right: 8px">关联关系</span>
					<Dropdown trigger="click" @on-click='searchRelation'>
		                <Button type="ghost" size="small" style='padding:3px 8px;width:120px'>
		                    <span class='search-data' :class="{'not_select':search_data.relation == ''}" style="padding-top: 2px;">{{search_data.relation ? search_data.relation : '请选择'}}</span>
		                    <div style='transform:scale(0.5);float: right'>
		                    	<Icon type="chevron-down" size='20'></Icon>
		                    </div>
		                </Button>
		                <DropdownMenu slot="list" style='width:116px'>
		                	<DropdownItem name="">请选择</DropdownItem>
		                    <DropdownItem v-for="item in configData.relation" :name="item" :key="item" :title='item'>{{item}}</DropdownItem>
		                </DropdownMenu>
		            </Dropdown>
				</div>
				<div>
					<span style="font-size:16px;margin-right: 8px">关联表</span>
					<Dropdown trigger="click" @on-click='searchTarget'>
		                <Button type="ghost" size="small" style='padding:3px 8px;width:120px'>
		                    <span class='search-data' :class="{'not_select':search_data.target == ''}" style="padding-top: 2px;">{{search_data.target ? search_data.target : '请选择'}}</span>
		                    <div style='transform:scale(0.5);float: right'>
		                    	<Icon type="chevron-down" size='20'></Icon>
		                    </div>
		                    
		                </Button>
		                <DropdownMenu slot="list" style='width:116px'>
		                	<DropdownItem name="">请选择</DropdownItem>
		                    <DropdownItem v-for="item in configData.table" :name="item.Name" :key="item">{{item.Name}}</DropdownItem>
		                </DropdownMenu>
		            </Dropdown>
				</div>
				
				<div>
					<span style="font-size:16px;margin-right: 8px">外键关联表</span>
					<Dropdown trigger="click" @on-click='searchForeignTarget'>
		                <Button type="ghost" size="small" style='padding:3px 8px;width:120px'>
		                    <span class='search-data' :class="{'not_select':search_data.foreign_key_target == ''}" style="padding-top: 2px;">{{search_data.foreign_key_target ? search_data.foreign_key_target : '请选择'}}</span>
		                    <div style='transform:scale(0.5);float: right'>
		                    	<Icon type="chevron-down" size='20'></Icon>
		                    </div>
		                </Button>
		                <DropdownMenu slot="list" style='width:116px'>
		                	<DropdownItem name="">请选择</DropdownItem>
		                    <DropdownItem v-for="item in configData.table" :name="item.Name" :key="item">{{item.Name}}</DropdownItem>
		                </DropdownMenu>
		            </Dropdown>
				</div>
			</div>
			<div style='margin-top: 25px;margin-bottom: -30px'>
				<button class='btn btn-search' @click='searchData'>查询</button>
				<button class='btn-cancel btn-export' @click='exportData'>批量导出</button>
			</div>
		</div>
		<div style='padding:35px 20px;background: #fff;margin-top: 16px'>
			<button class='btn btn-hover' @click='addRelation'>创建关联</button>
			<div style="padding:1px">
				<Table :columns="relationList" :data="relationData" stripe></Table>
			</div>
	    	<div style='overflow: hidden'>
	    		<Page :current='pagination.page' :total="pagination.rowCount" :page-size='pagination.pageSize' style='float: right;margin: 20px 0;' @on-change='changePage'></Page>
	    	</div>
		</div>
		<!-- 创建关联 -->
        <Modal v-model="modal" width="600" @on-cancel="cancel">
            <p slot="header">
                <span>{{dataId?'编辑关联':'创建关联'}}</span>
            </p>
            <div>
               <Form :label-width='90'>
                    <FormItem label='数据表'>
                    	<p slot='label'><span class='star'>*</span>数据表</p>
                    	<Select v-model='formItem.table' @on-change='selectTable'>
                            <Option v-for="item in configData.table" :value="item.Name" :key="item"></Option>
                        </Select>
                    </FormItem>
                    <FormItem label='关联表'>
                    	<p slot='label'><span class='star'>*</span>关联表</p>
                    	<Select v-model='formItem.target' @on-change='selectTarget'>
                            <Option v-for="item in configData.table" :value="item.Name" :key="item"></Option>
                        </Select>
                    </FormItem>
                    <FormItem label='关联关系'>
                    	<p slot='label'><span class='star'>*</span>关联关系</p>
                        <Select v-model='formItem.relation' @on-change='selectRelation'>
                            <Option v-for="item in configData.relation" :value="item" :key="item">{{item}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label='关联昵称'>
                        <Input v-model='formItem.targeted' placeholder='请输入名称'></Input>
                    </FormItem>
                    <FormItem label='外键'>
                    	<p slot='label'><span class='star'>*</span>外键</p>
                        <Select v-model='formItem.foreign_key'>
                            <Option v-for="item in foreignKey" :value="item.Field" :key="item">{{item.Field}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label='外键关联表'>
                    	<Select v-model='formItem.foreign_key_target'>
                            <Option value="">请选择</Option>
                            <Option v-for="item in configData.table" :value="item.Name" :key="item"></Option>
                        </Select>
                    </FormItem>
                </Form>
            </div>
            <div slot="footer" style='padding-top:0'>
                <button class='btn-cancel' @click="cancel">取消</button>
                <button class='btn-sure' @click="sure">确认</button>
            </div>
        </Modal>
	</div>
</template>
<script type="text/javascript">
    import axios from 'axios'
	export default{
		data(){
			return{
				modal:false,
				relationList: [
                    {
                        title: '数据表',
                        key: 'table'
                    },
                    {
                        title: '数据关系',
                        key: 'relation'
                    },
                    {
                        title: '关联表',
                        key: 'target'
                    },
                    {
                        title: '外键',
                        key: 'foreign_key'
                    },
                    {
                        title: '外键关联表',
                        key: 'foreign_key_target'
                    },
                    {
                        title: '创建时间',
                        key: 'created_at',
                        width:160,
                        render: (h, params) => {
                            return h('div', [
                                h('span', this.format(params.row.created_at))
                            ]);
                        }
                    },
                     {
                        title: '更新时间',
                        key: 'updated_at',
                        width:160,
                        render: (h, params) => {
                            return h('div', [
                                h('span', this.format(params.row.updated_at))
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width:110,
                        render: (h, params) => {
                            return h('div', [
                                h('span', {
                                    style: {
                                        color:'#06A0FD',
                                        cursor:'pointer',
                                        marginRight:'8px'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row)
                                        }
                                    }
                                }, '编辑'),
                                h('span', {
                                    style: {
                                        color:'#06A0FD',
                                        cursor:'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            this.del(params.row)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                relationData: [],
                pagination:{
                    page:1
                },
                configData:{},
                formItem:{
                	table:'',
                    relation:'',
                    target:'',
                    targeted:'',
                    foreign_key:'',
                    foreign_key_target:'',
                },
                foreign_key:'',
                dataId:0,
                foreignKey:[],
                //搜索
                search_data:{
                	table:'',
	                relation:'',
	                target:'',
	                foreign_key_target:''
                }
			}
		},
		created(){
            //获取配置信息
            this.fetch('/home/app/schema/info/relation').then(res=>{
                if(res&&res.data.data&&res.data.code){
                    this.configData = res.data.data;
                }
            })
            this.$bus.on('select_submenu',this.selectSubmenu)
            this.getData();
            
        },
        destroyed() {
            this.$bus.off('select_submenu', this.selectSubmenu);
        },
        methods:{
            selectSubmenu(res){
                this.search_data = {
                    table:'',
                    relation:'',
                    target:'',
                    foreign_key_target:''
                }
                this.getData();
            },
            getData(page){
                let url = '/home/app/schema/relation?page='+this.pagination.page;
                
                if(this.search_data.table){
                    url += '&table=' + this.search_data.table;
                }
                if(this.search_data.relation){
                    url += '&relation=' + this.search_data.relation;
                }
                if(this.search_data.target){
                    url += '&target=' + this.search_data.target;
                }
                if(this.search_data.foreign_key_target){
                    url += '&foreign_key_target=' + this.search_data.foreign_key_target;
                }
                this.fetch(url).then(res=>{
                    if(res&&res.data.data&&res.data.code){
                        this.relationData = res.data.data.data;
                        this.pagination = res.data.data.pagination;
                    }
                })
            },
            changePage(page){
                this.pagination.page = page;
                this.getData(page);
            },
            //搜索
            searchTable(table){
            	this.search_data.table = table;
            },
            searchRelation(relation){
            	this.search_data.relation = relation;
            },
            searchTarget(target){
            	this.search_data.target = target;
            },
            searchForeignTarget(foreignTarget){
            	this.search_data.foreign_key_target = foreignTarget;
            },
            searchData(){
                this.pagination.page = 1;

                let url = '/home/app/schema/relation';
                let option = []
                
                if(this.search_data.table){
                    option.push('table=' + this.search_data.table)
                }
                if(this.search_data.relation){
                    option.push('relation=' + this.search_data.relation)
                }
                if(this.search_data.target){
                    option.push('target=' + this.search_data.target)
                }
                if(this.search_data.foreign_key_target){
                    option.push('foreign_key_target=' + this.search_data.foreign_key_target)
                }
                if(option.length){
                    url += '?' + option.join('&')
                }
            	this.fetch(url).then(res=>{
                    if(res&&res.data.data&&res.data.code){
                        this.relationData = res.data.data.data;
                        this.pagination = res.data.data.pagination;
                    }
                })
            },
            //导出
            exportData(){
            	window.open(axios.defaults.baseURL+`/home/app/schema/export/relation?token=${axios.defaults.headers.common["Token"]}&baastoken=${axios.defaults.headers.common["BaasToken"]}&table=${this.search_data.table}&relation=${this.search_data.relation}&target=${this.search_data.target}&foreign_key_target=${this.search_data.foreign_key_target}`)
            },
            //创建密钥
            addRelation(){
                this.modal = true;
                this.dataId = 0;
                this.formItem = {}
                this.search_data.table = '';
                this.search_data.relation = '';
                this.search_data.target = '';
                this.search_data.foreign_key_target = '';
            },
            cancel(){
                this.foreignKey = [];
                this.modal = false;
            },
            
            //选择数据表
            selectTable(table){
                if(table){
                    if(this.formItem.relation){
                        if(this.formItem.relation == 'belongsTo' || this.formItem.relation == 'belongsToMany'){
                            this.getForeignKey(table);
                        }else{
                            if(!this.formItem.target){
                                this.$Message.warning('请选择关联表')
                            }else{
                                this.getForeignKey(this.formItem.target);
                            }
                        }
                    }
                }
               
            	
            },
            //选择关联表
            selectTarget(target){
                
                if(target){
                    if(this.formItem.relation){
                        if(this.formItem.relation == 'belongsTo' || this.formItem.relation == 'belongsToMany'){
                            this.getForeignKey(target);
                        }else{
                            if(!this.formItem.table){
                                this.$Message.warning('请选择数据表')
                            }else{
                                this.getForeignKey(this.formItem.table);
                            }
                        }
                    }
                }
                
            },
            //选择关联关系
            selectRelation(relation){
                if(relation){
                    
                    if(relation == 'belongsTo' || relation == 'belongsToMany'){
                        if(!this.formItem.table){
                            this.$Message.warning('请选择数据表')
                        }else{
                            this.getForeignKey(this.formItem.table);
                        }
                    }else{
                        if(!this.formItem.target){
                            this.$Message.warning('请选择关联表')
                        }else{
                            this.getForeignKey(this.formItem.target);
                        }
                    }
                }
                
            },

            //获取外键
            getForeignKey(table){
            	this.fetch('/home/app/schema/relation/field/'+table).then(res=>{
		                if(res&&res.data.data&&res.data.code){
		                    this.foreignKey = res.data.data;
                            if(this.dataId){
                                this.formItem.foreign_key = this.foreign_key;
                            }
		                }
		            })
            },
            sure(){
            	if(!this.formItem.table){
            		this.$Message.warning('请选择数据表')
            		return;
            	}
            	if(!this.formItem.target){
            		this.$Message.warning('请选择关联表')
            		return;
            	}
            	if(!this.formItem.relation){
            		this.$Message.warning('请选择关联关系')
            		return;
            	}
            	
            	if(!this.formItem.foreign_key){
            		this.$Message.warning('请选择外键')
            		return;
            	}
                let data = {
                    table:this.formItem.table,
                    relation:this.formItem.relation,
                    target:this.formItem.target,
                    targeted:this.formItem.targeted,
                    foreign_key:this.formItem.foreign_key,
                    foreign_key_target:this.formItem.foreign_key_target
                }
                if(this.dataId){
                    data.id = this.dataId;
                }
                this.fetch('/home/app/schema/add/relation',data).then(res=>{
                    if(res&&res.data.data&&res.data.code){
                        this.$Message.success(this.dataId?'编辑成功':'新增成功')
                        this.getData();
                        this.foreignKey = [];
                        this.modal = false;
                    }
                })
            },
            edit(row){
                this.dataId = row.id;
                this.modal = true;
                this.fetch('/home/app/schema/relation/'+row.id).then(res=>{
                    if(res&&res.data.data&&res.data.code){
                        let data = res.data.data;
                        this.formItem = data;
                        this.foreign_key = data.foreign_key;
                        if(data.relation == 'belongsTo' || data.relation == 'belongsToMany'){
                            this.getForeignKey(data.table)
                        }else{
                            this.getForeignKey(data.target)
                        }
                    }
                })
            },
            del(row){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定删除吗</p>',
                    onOk: () => {
                        this.fetch('/home/app/schema/del/relation/'+row.id).then(res=>{
                            if(res&&res.data.data&&res.data.code){
                                this.$Message.success('删除成功')
                                this.getData();
                            }
                        })
                    }
                });
                
            }
        }
	}
</script>
<style scoped>
	.btn-search{
		width:60px;height:30px;margin-right: 16px;border-radius: 3px
	}
	.btn-export{
		width:90px;height:30px;line-height: 30px;border-radius: 3px
	}
    .search-data{
        float:left;
        width:80%;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow:ellipsis
    }
    .not_select{
        color:#c3cbd6;
    }
</style>
